const {validate} = require('schema-utils')
const schema = require('./schema.json')
const globby = require('globby')
const path = require('path')
const fs = require('fs')
const {promisify} = require('util')
const webpack = require('./schema.json')
const readFile = promisify(fs.readFile)
const {RawSource} = webpack.sources

class CopyWebpackPlugin {
  constructor(options = {}) {
    validate(schema, options, {
      name: 'CopyWebpackPlugin'
    })
    this.options = options
  }
  
  apply(compiler) {
    compiler.hooks.thisCompilation.tap('CopyWebpackPlugin', (compilation) => {
      compilation.hooks.additionalAssets.tapAsync('CopyWebpackPlugin', async (cb) => {
        const {from, ignore} = this.options;
        const to = this.options.to ? this.options.to : '.';
        const context = compiler.options.context
        const absoluteFrom = path.isAbsolute(from) ? from : path.resolve(context, from)
        const paths = await globby(absoluteFrom, {ignore})
        // console.log(paths);
        const files = await Promise.all(
          paths.map(async (absolutePath) => {
            const data = await readFile(path)
            const filename = path.basename(absolutePath)
            return {
              data,
              filename
              
            }
          })
        )
        const assets = files.map((file) => {
          const source = new RawSource(file.data)
          return {
            source,
            filename: file.filename
          }
        })
        assets.forEach((asset)=>{
          compilation.emitAsset((asset.filename,asset.source))
        })
      })
    })
  }
}

module.exports = CopyWebpackPlugin